import { computed, ref, watch } from "@vue/composition-api";
import { useFetch } from "./useFetch";

export const useInfinityList = (url, options = {}) => {
  const queryParams = computed(() => ({
    current: 0,
    size: 20
  }));

  const mergedOptions = computed(() => {
    return {
      method: "post",
      immediate: false,
      ...options,
      params: { ...options.params, ...queryParams }
    };
  });

  const { loading, error, data, fetch } = useFetch(url, mergedOptions);

  const items = ref([]);
  const total = ref(0);
  const finished = ref(false);

  watch(data, () => {
    if (!data.value) return;
    total.value = data.value.total;
    items.value = [...items.value, ...data.value.records];
  });

  watch(items, () => {
    if (loading.value) {
      finished.value = false;
    } else if (items.value.length >= total.value) {
      finished.value = true;
    }
  });

  function load() {
    queryParams.value.current += 1;
    fetch();
  }

  function reload() {
    reset();
    load();
  }

  function reset() {
    queryParams.value.current = 0;

    items.value = [];
    total.value = 0;
    finished.value = false;
  }

  return {
    error,
    loading,
    finished,
    items,
    total,
    api: {
      load,
      reload
    }
  };
};
